package com.santiao.youxiang.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Base64
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.gyf.immersionbar.ImmersionBar
import com.santiao.publics.ui.SettingFragment
import com.santiao.youxiang.MainActivity
//import com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
import kotlin.apply
//import kotlin.jvm.java
import com.santiao.youxiang.R
import com.santiao.youxiang.bean.EmailBean
import com.santiao.youxiang.bean.lzy.HistoryBean
import com.santiao.youxiang.database.hleper.PostDatabaseHelper
import com.santiao.youxiang.databinding.ActivitySearchBinding

import com.santiao.youxiang.ext.thrillClickListener
import com.santiao.youxiang.ui.adapter.EmailAdapter
import com.santiao.youxiang.ui.fragment.HomeViewModel
import com.santiao.youxiang.ui.widget.LoadingDiaLog
import com.sun.mail.imap.IMAPFolder
import com.sun.mail.imap.IMAPStore
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.nio.charset.Charset
import java.util.Calendar
import java.util.Date
import java.util.Properties
import javax.mail.Folder
import javax.mail.Message
import javax.mail.Multipart
import javax.mail.Part
import javax.mail.Session
import javax.mail.internet.MimeMessage
import javax.mail.search.AndTerm
import javax.mail.search.ReceivedDateTerm
import javax.mail.search.SearchTerm
import kotlin.toString

class emailSearcheActivity: AppCompatActivity() {
    private lateinit var binding: ActivitySearchBinding
//    private lateinit var lzyadsUtils: com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
var type_a="" //1 医保 2：社保
    var type=1
    private lateinit var loadingDiaLog: LoadingDiaLog

    var slePosition=1

//    private val HviewModel: HomeViewModel by viewModels()
        private lateinit var HviewModel: HomeViewModel
    private lateinit var eadapter: EmailAdapter

    var struri=""
    // 在类顶部定义
    val REQUEST_STORAGE_PERMISSION = 1001  // 可以是任意唯一整数

    companion object {
        // 定义一个静态方法来创建Intent
        // 定义一个静态方法来创建Intent并携带uri数据
        fun startActivity(context: Context?/*, type: String*/) {

            val intent = Intent(context, emailSearcheActivity::class.java).apply {

//                putExtra("type", type)

            }

            context!!.startActivity(intent)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySearchBinding.inflate(layoutInflater)
        setContentView(binding?.root)
        type_a= intent.getStringExtra("type").toString()
        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarDarkFont(true)
            .transparentNavigationBar()
            .init()
        initViews(type_a)
        initRv()

        SettingFragment.adLoad3(0,null,null,this,this);
    }



     fun initViews(type: String) {
//        initad()
         HviewModel= MainActivity.HviewModel

         initclick()

        binding.ivBack.setOnClickListener { onBackPressed() }

    }

    fun initclick(){

//        binding.llQq.thrillClickListener {
//            AddAccountActivity.startActivity(this,"1")
//        }
//
//        binding.llE163.thrillClickListener {
//            AddAccountActivity.startActivity(this,"2")
//        }
//
//        binding.llE126.thrillClickListener {
//            AddAccountActivity.startActivity(this,"3")
//        }
        val currentPost= HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
        val time=getStartAndEndTimestamp(intent.getIntExtra("year",2025),
            intent.getIntExtra("month",2),
            intent.getIntExtra("day",26))
        // 监听文本变化
        binding.searchEditView.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {
                // 在文本变化之前触发
            }

            override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {
                // 在文本变化时触发
                // 这里可以获取到文本的变化，例如：
//                val inputText = charSequence.toString()
//                println("输入的文本: $inputText")


            }

            override fun afterTextChanged(editable: Editable?) {
                // 在文本变化之后触发
            }
        })


        binding.tvSearch.thrillClickListener{
//            finish()

            PostDatabaseHelper(this@emailSearcheActivity,HviewModel).insertOrUpdateHistory(HistoryBean(null,binding.searchEditView.text.toString(),System.currentTimeMillis()))
            if (currentPost!=null) {
                loadingDiaLog=LoadingDiaLog(this@emailSearcheActivity,"获取邮件中...")
                loadingDiaLog.show()
                tryToLoginEmail(currentPost.pAddress, currentPost.pCode,time.first,time.second,binding.searchEditView.text.toString())
            }

            HviewModel.refreshEmail.observe(this@emailSearcheActivity){
                if (it==2){
                    loadingDiaLog=LoadingDiaLog(this@emailSearcheActivity,"更新状态中...")
                    loadingDiaLog.show()
                    tryToLoginEmail(currentPost!!.pAddress, currentPost.pCode,time.first,time.second,binding.searchEditView.text.toString())
                    HviewModel.refreshEmail.value=1
                }
            }

        }


//        binding.searchClean.thrillClickListener{
//            binding.flKeyword.removeAllViews()
//            PostDatabaseHelper(this@emailSearcheActivity,HviewModel).deleteAllHistory()
//        }
//
//        binding.searchSearch.thrillClickListener {
//            binding.searchEditView.requestFocus()
//            showKeyboard(binding.searchEditView)
//        }
//        binding.searchConfirmTextView.thrillClickListener{
//            if (binding.searchEditView.text.isNullOrBlank()){
//                Toast.makeText(this@emailSearcheActivity, "请输入搜索关键字", Toast.LENGTH_SHORT).show()
//                return@thrillClickListener
//            }else{
//                // 增加关键字
//                binding.flKeyword.addView(binding.searchEditView.text.toString()) { content ->
//                    val bundle= Bundle()
//                    bundle.putInt("type", 1)
//                    bundle.putString("keywords",content)
////                    forward<ResultActivity>(this@SearchActivity,bundle)
//                }
//                val bundle= Bundle()
//                bundle.putInt("type", 1)
//                bundle.putString("keywords",binding.searchEditView.text.toString())
////                forward<ResultActivity>(this@SearchActivity,bundle)
//            }
//
//        }



    }

    fun switchItem(position: Int) {

    }

    fun initRv(){


        eadapter=EmailAdapter()


        val layoutManager = LinearLayoutManager(this@emailSearcheActivity, LinearLayoutManager.VERTICAL, false)
        Log.e("initrv: ", "2")
//        Camadapter

        binding!!.rvEmail?.layoutManager = layoutManager
        binding!!.rvEmail?.adapter = eadapter




        //item整体点击事件
        eadapter?.setOnItemClickListener { adapter, view, position ->

//            val item = adapter.data[position] as HomeCamBean  // 明确类型
//            val userId = item.userId.toString()
//            val chanelId = item.channelID.toString()
//            val token = item.token.toString()

            val bundle=Bundle()
            bundle.putInt("type", 0)
            bundle.putSerializable("email", eadapter.data.get(position))
            EamilDetailActivity.startActivity(this@emailSearcheActivity,bundle)
//            var userIds= adapter.data.get(0)





//            val cam = LitePal.where("userId = ? ", userId).findFirst(liveCam::class.java)



        }

        eadapter!!.setOnItemChildClickListener { _, view, position ->
//            if (view.id == R.id.ll_del) {
//                // 删除逻辑
//                delFromdb(billadapter!!.data.get(position).id.toString())
//                billadapter!!.removeAt(position)
//                billadapter!!.notifyItemRemoved(position)
//
//            }
            val bundle=Bundle()
//            bundle.putInt("type", type)
//            bundle.putSerializable("email", itemData)
//            LZYBaseActivity.forward<EmailDetailActivity>(mContext,bundle)

        }


    }



fun initData(){



}


    fun   initad() {
//        myContext = requireContext()
//        lzyadsUtils=
//            com.lazyliuzy.commonui.utils.lzy.LZYADSUtils("Task1Activity", this@Task1Activity)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.loadSimpleAd1(com.lazyliuzy.commonui.databinding.ActivityTask1Binding.flAd)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.showAdCpTurn()

    }


    private fun hideKeyboard(view: View) {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    private fun showKeyboard(view: View) {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
    }

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (v is EditText) {
                val outRect = Rect()
                v.getGlobalVisibleRect(outRect)
                if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
                    v.clearFocus()
                    hideKeyboard(v)
                }
            }
        }
        return super.dispatchTouchEvent(event)
    }


    @OptIn(DelicateCoroutinesApi::class)
    fun tryToLoginEmail( email: String, authCode: String,startTime:Long,endTime:Long,keywords:String) {
        // 在后台线程执行 IMAP 请求
//        LZYLog.i("lzyemailget","$email, $authCode, $startTime,$endTime")
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? =null
            val domain = email.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                }
            }
            val imapPort = "993"
            val properties = Properties()
            properties["mail.store.protocol"] = "imaps"
            properties["mail.imaps.host"] = imapHost
            properties["mail.imaps.port"] = imapPort

            // 获取Session
            val session = Session.getInstance(properties)
            try {
                // 创建 IMAP 存储连接
                val store = session.getStore("imaps")
                store.connect(imapHost, email, authCode)  // 使用授权码登录
                val folderName=
                    if (HviewModel.currentPostType.value=="126"||HviewModel.currentPostType.value=="163"){
                        when(HviewModel.currentEmailType.value){
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "已发送"
                            4 -> "草稿箱"
                            5 -> "垃圾邮件"
                            6 -> "已删除"
                            else -> if (HviewModel.currentPostType.value=="126") "病毒邮件" else "病毒文件夹"
                        }
                    }else if (HviewModel.currentPostType.value=="aliyun") {
                        when(HviewModel.currentEmailType.value){
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "已发送"
                            4 -> "草稿"
                            5 -> "垃圾邮件"
                            6 -> "已删除邮件"
                            else -> "INBOX"
                        }
                    }else{
                        when(HviewModel.currentEmailType.value) {
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "Sent Messages"
                            4 -> "Drafts"
                            5 -> "Junk"
                            6 -> "Deleted Messages"
                            else -> "INBOX"
                        }
                    }
                val f=store.getFolder(folderName) as IMAPFolder
                store as IMAPStore
                val idMap: MutableMap<String, String> = HashMap()
                idMap["name"] = "mail poster" // 这里是一个姓名，可以随便写
                idMap["version"] = "7.26"
                idMap["os"] = "android"
                idMap["os-version"] = "1.0.0"
                idMap["vendor"] = "hello" // 随便写
                idMap["contact"] = "${email}" // 是一个邮箱
                store.id(idMap)
                f.open(Folder.READ_ONLY)  // 打开文件夹（只读模式）
                // 获取所有邮件
                val emails= mutableListOf<EmailBean>()
                if (f.messageCount>0){
                    //获取所有邮件
                    val messages: Array<Message>
                    if (type==0){
                        val startDate = Date(startTime)
                        val endDate = Date(endTime)
                        val startDateTerm = ReceivedDateTerm(ReceivedDateTerm.GE, startDate)  // 大于等于 startDate
                        val endDateTerm = ReceivedDateTerm(ReceivedDateTerm.LE, endDate)      // 小于等于 endDate
                        val searchTerm = AndTerm(startDateTerm, endDateTerm)
                        messages = f.search(searchTerm)
                    }else{
                        val searchTerm = object : SearchTerm() {
                            override fun match(message: Message?): Boolean {
                                return try {
                                    val subject = message?.subject ?: ""
                                    val from = decodeBase64AndKeepEmail(message?.from?.joinToString(", ")!!) ?: ""
                                    // 检查主题和发件人是否包含关键字
                                    subject.contains(keywords, ignoreCase = true) || from.contains(keywords, ignoreCase = true)
                                } catch (e: Exception) {
                                    false
                                }
                            }
                        }
                        messages = f.search(searchTerm)
                    }
                    // 输出邮件内容
                    for (message in messages) {
                        message as MimeMessage
                        val emailFrom=decodeBase64AndKeepEmail(message.from.joinToString(", ")).split(" ")
//                        LZYLog.i("lzyemailget","type:${message.contentType}")
                        val contentm= getMailContent(message,true)
                        emails.add(
                            EmailBean(
                                f.getUID(message),
                                emailFrom[0],
                                emailFrom[1],
                                decodeBase64AndKeepEmail(
                                    message.getRecipients(Message.RecipientType.TO)
                                        .joinToString(", ")
                                ),
                                message.sentDate,
                                message.subject,
                                contentm?:""
                            )
                        )
                    }
                }
                withContext(Dispatchers.Main) {
                    emails.reverse()
                }
                // 完成操作后关闭文件夹
                f.close(false)
                store.close()
                withContext(Dispatchers.Main) {
                    eadapter.data.clear()
                    if (emails.isEmpty()){
//                        binding.noEmail.visibility= View.VISIBLE
//                        binding.emailRecyclerView.visibility= View.GONE
//                        eadapter.setEmptyView(R.layout.layout_empty)
                        eadapter.setEmptyView(R.layout.layout_empty)

                        val emptyView = eadapter?.emptyLayout?.findViewById<TextView>(R.id.tv_des)
                        emptyView!!.text="未搜索到相关结果"
                        Toast.makeText(this@emailSearcheActivity,"未搜索到相关结果~", Toast.LENGTH_SHORT).show()
                    }else{
//                        binding.noEmail.visibility= View.GONE
//                        binding.emailRecyclerView.visibility= View.VISIBLE
//                        Log.e("tryToLoginEmail: eadapter", emails.toString())
                        eadapter.setList(emails)
                        eadapter.notifyDataSetChanged()
//                        Toast.makeText(this@emailSearcheActivity,"获取邮件信息成功~", Toast.LENGTH_SHORT).show()
                    }

//                    adapter=ItemEmailAdapter(this@emailSearcheActivity, emails,1)
//                    binding.emailRecyclerView.adapter=adapter
//                    binding.emailRecyclerView.layoutManager= LinearLayoutManager(this@emailSearcheActivity, LinearLayoutManager.VERTICAL,false)
                    loadingDiaLog.dismiss()

                }
            } catch (e: Exception) {
                e.printStackTrace()
//                LZYLog.i("lzyemail", "邮件：登录连接失败")
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@emailSearcheActivity,"获取邮件信息失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }


    fun decodeBase64AndKeepEmail(encodedString: String): String {
        // 正则表达式用于匹配 Base64 编码部分，且不区分大小写
        val regex = "=\\?(?i)utf-8\\?b\\?([^?]+)?\\?="

        val matchResults = regex.toRegex().findAll(encodedString)
        val decodedParts = mutableListOf<String>()
        var lastEnd = 0

        // 遍历所有匹配项
        for (match in matchResults) {
            // 添加非 Base64 编码的部分
            decodedParts.add(encodedString.substring(lastEnd, match.range.first))

            // 提取 Base64 编码部分
            val base64Encoded = match.groupValues[1]

            // 解码 Base64 字符串
            val decodedBytes = Base64.decode(base64Encoded, Base64.NO_WRAP)
            val decodedText = String(decodedBytes, Charset.forName("UTF-8"))

            // 添加解码后的文本
            decodedParts.add(decodedText)

            lastEnd = match.range.last + 1
        }

        // 如果还有剩余的部分，直接添加
        decodedParts.add(encodedString.substring(lastEnd))

        return decodedParts.joinToString("")
    }

    fun getStartAndEndTimestamp(year: Int, month: Int, day: Int): Pair<Long, Long> {
        // 获取起始时间（当天 00:00:00.000）
        val calendarStart = Calendar.getInstance().apply {
            set(year, month - 1, day, 0, 0, 0)
            set(Calendar.MILLISECOND, 0)
        }
        val startTimestamp = calendarStart.timeInMillis

        // 获取结束时间（第二天 00:00:00.000）
        val calendarEnd = Calendar.getInstance().apply {
            set(year, month - 1, day, 0, 0, 0)
            add(Calendar.DAY_OF_MONTH, 1)  // 加一天，表示第二天的 00:00:00.000
            set(Calendar.MILLISECOND, 0)
        }
        val endTimestamp = calendarEnd.timeInMillis
        return Pair(startTimestamp, endTimestamp)
    }

    /**
     * 解析邮件，把得到的邮件内容保存到一个StringBuffer对象中，解析邮件 主要是根据MimeType类型的不同执行不同的操作，一步一步的解析
     */
    @Throws(java.lang.Exception::class)
    fun getMailContent(part: Part, first:Boolean): String{
        val bodytext=StringBuffer()
        val contenttype: String = part.getContentType()
        val nameindex = contenttype.indexOf("name")
        var conname = false
        if (nameindex != -1) conname = true
        if (part.isMimeType("text/plain") && !conname) {
            if (first)
                return part.getContent() as String
        } else if (part.isMimeType("text/html") && !conname) {
            bodytext.append(part.getContent() as String)
        } else if (part.isMimeType("multipart/*")) {
            val multipart = part.getContent() as Multipart
            val counts = multipart.count
            for (i in 0 until counts) {
                bodytext.append(getMailContent(multipart.getBodyPart(i),false))
            }
        } else if (part.isMimeType("message/rfc822")) {
            getMailContent(part.getContent() as Part,false)
        } else {
        }
        return bodytext.toString()
    }
    

}